<?php
class DataTableCallback
{
	private $database;
	private $recordID;
	private $userID;
	
	private $associatedFiles;
	
	public function __construct($database,$userID)
	{
		$this->userID = $userID;
//		echo "UserID = ".$userID."\n";
		$this->database = $database;
		$this->recordID = $_POST['RecordID'];
	}
	
	private function getFiles($tablename) // with multiple files this is so different that it is better to treat it completely apart
	{
		// this function gets all existing files for this resource plus a new one if there is one (via $_FILES and $_POST)
		// it creates a new file in ResourceFiles/ ...
		// we will elsewhere have to create a new resource with all files added
		// we will also have to delete any indicated for deletion via $_POST ... next version!
		
			$files = array();
			
			if($_POST['RecordID']!=-1) //there will only be existing ones if there is actually a resource!
			{
				// any existing ones?
				$sql = "SELECT * FROM ".$tablename." WHERE ResourceIDP = ".$_POST['RecordID'];
				$database = $this->database->Recopy();
				$database->ExecuteSQL($sql);
				while($row = $database->getRow())
				{
					$aFile= array();
					$aFile['PhysicalFileNumber'] = $row['PhysicalFileNumber'];
					$aFile['FileName'] = $row['FSFileName'];
					$aFile['FileSize'] = $row['FSFileSize'];
					$aFile['FileType'] = $row['FSFileType'];
					array_push($files,$aFile);
				}
			}	
			// a new one?
			if($_FILES['InsertRecord_Files_FSFileSize']['tmp_name'] != "")
			{
				$aFile= array();
				$aFile['FileName'] = $_FILES['InsertRecord_Files_FSFileSize']['name'];
				$localname = $_FILES['InsertRecord_Files_FSFileSize']['tmp_name'];
				$aFile['FileType'] = $_FILES['InsertRecord_Files_FSFileSize']['type'];
				$fp      = fopen($localname, 'r');
				$aFile['FileSize'] = filesize($localname);
				fclose($fp);
				
				$sql="INSERT INTO ".$tablename." (ResourceIDP,FSFileName,FSFileSize,FSFileType) VALUES('".$this->recordID."','".$aFile['FileName']."','".$aFile['FileSize']."','".$aFile['FileType']."')";
				$database=$this->database->Recopy();
				$database->ExecuteSQL($sql);
//	//			echo $sql."<br>\n";
//	//			echo $sql.mysql_error()."<br>";
//	//			echo mysql_insert_id()."<br>";
				$aFile['PhysicalFileNumber'] = mysql_insert_id();
				
				$sql="UPDATE ".$tablename." SET PhysicalFileNumber = ".$aFile['PhysicalFileNumber']." WHERE FileID = ".$aFile['PhysicalFileNumber'];
//				echo $sql."<br>\n";
				$database->ExecuteSQL($sql);

				$localname = $_FILES['InsertRecord_Files_FSFileSize']['tmp_name'];
//				echo "localname = ".$localname."<br>.\n";
				$NewName = $GLOBALS['DOCUMENT_ROOT']."ResourceFiles/Files_FSFile_".$aFile['PhysicalFileNumber'];
//				echo "newname = ".$NewName."<br>.\n";
	//			echo "Copy ".$localname." to ".$NewName."<br>\n";
				move_uploaded_file($localname,$NewName);		
				array_push($files,$aFile);
				
				$date = new DateTime();
				$sql = "INSERT INTO Actions (ResourceID, ActionTypeID, ActionDate, ActionUserID, ActionComment) ";
				$sql .= "VALUES ('".$this->recordID."','5','".$date->format('Y-m-d H:i:s')."','".$_POST['UserID']."','".$aFile['FileName']." added')";
//				echo $sql."<br>";
				$database->ExecuteSQL($sql);
		
				
			}			

			$this->associatedFiles = $files;
	}
	
	private function InsertIntoTable($database,$tablename,$array,$ParentTableID)
	{
//		echo "Going to insert into $tablename<br>";
	//	print_r($array);
	//	echo "<br>";
	//	echo $ParentTableID."<br>";
		// Need to get a new ID if it is parent Table
		// Need to insert this ID if not - compare $tablename with $_POST['DBTableName'] to decide
		
	 	$isParentTable = ($tablename==$_POST['DBTableName']);
	
		$table = new DBTable($database,$tablename);
		$tableStructure = $table->getTableStructure();
	//	print_r($tableStructure);
		
		$repeatWeeks = 0;
		if(isset($_POST['RepeatWeeks']))$repeatWeeks = $_POST['RepeatWeeks'];
		for($i=0;$i <= $repeatWeeks;$i++)
		{
			
			$sql = "INSERT INTO ".$tablename." (";
			if($isParentTable) 
				$sql.= "CreatedWhen,CreatedBy,";
	
			$includeSQL = false;
			foreach($array as $key => $value)
			{
//				echo $key."<br>";
				if(isset($tableStructure[$key]))
					if(($tableStructure[$key]=="enum('multilevelmultienum')")||($tableStructure[$key]=="enum('multienum')"))continue;
								
				if($key=='FSFileName'); // ignore
				elseif($key=='FSFileSize'); // ignore
				elseif($key=='FSFileType'); // ignore
	//			elseif($key=='FSFileContents'); // ignore
				elseif(isset($tableStructure[$key]))
				{
	//				echo $tableStructure[$key]."<br>";
					if(($tableStructure[$key]=="enum('multilevelmultienum')")||($tableStructure[$key]=="enum('multienum')"));
					else 
					{
						$sql .= $key.",";
						$includeSQL=true; // only run the sql if there is a field to add
					}
				}
				elseif($key=='MAXFILESIZE')
				{
					$this->getFiles($tablename);
					continue;
				}
			}
			if(!$isParentTable)$sql .= substr($_POST['DBTableName'],0,-1)."IDP,";
			$sql = substr($sql,0,strlen($sql)-1).") VALUES (";
			$datetime = new DateTime("now");
			if($isParentTable) 
				$sql.= "'".$datetime->format("Y-m-d H:i")."','".$this->userID."',";
			foreach($array as $key => $value)
			{
				if(isset($tableStructure[$key]))
					if(($tableStructure[$key]=="enum('multilevelmultienum')")||($tableStructure[$key]=="enum('multienum')"))continue;
				
				if($key=='FSFileName'); // ignore
				elseif($key=='FSFileSize'); // ignore
				elseif($key=='FSFileType'); // ignore
	//			elseif($key=='FSFileContents'); // ignore
				elseif(isset($tableStructure[$key]))
				{
//					echo $key."<br>\n";
					$sql .= "'".addslashes($value)."',";
				}
			}
			if(!$isParentTable)$sql .= $ParentTableID.",";
			$sql = substr($sql,0,strlen($sql)-1).")";
	
			$parentTableID = -1;
	//		echo $sql." includeSQL = ".$includeSQL."<br>";
			if($includeSQL)
			{
				$database->ExecuteSQL($sql);
	//			echo $sql.mysql_error()."<br>";
	//			echo mysql_insert_id()."<br>";
				$EventID = mysql_insert_id();
				$parentTableID = $EventID;
			}
			// are there any special fields (eg multienumerations)
	
			foreach($array as $key => $value)
			{
	//			echo $key."<br>";
				if(isset($tableStructure[$key]))
				{
	//				echo $tableStructure[$key]."<br>";
					if(($tableStructure[$key]=="enum('multilevelmultienum')")||($tableStructure[$key]=="enum('multienum')"))
					{
	//					print_r ($_POST["InsertRecord_".$tablename."_".$key]);
	//					echo "<br>";
	//					echo "Tablename = ".$tablename."<br>";
						if(isset($_POST["InsertRecord_".$tablename."_".$key]))
						{
							foreach($_POST["InsertRecord_".$tablename."_".$key] as $value)
							{
								$sql = "INSERT INTO ".$key."s (".substr($tablename,0,-1)."ID,".$key."NameID) VALUES (".$ParentTableID.",".$value.")";
	//							echo $sql."<br>";
								$database->ExecuteSQL($sql);
	//							echo $sql.mysql_error()."<br>";
	//							echo mysql_insert_id()."<br>";
								
							}
						}
					}
				}
			}
	
	//		echo $keyValues['Start'];
			if(isset($keyValues['Start']))
			{
				$time = new DateTime($keyValues['Start']);
				date_modify($time,"+7 day");
				$keyValues['Start']=$time->format("Y-m-d H:i");
			}
	
	//		echo $keyValues['End'];
			if(isset($keyValues['End']))
			{
				$time = new DateTime($keyValues['End']);
				date_modify($time,"+7 day");
				$keyValues['End']=$time->format("Y-m-d H:i");
			}
			
			// if this is a file resource need to create all entries in table 
//			echo "Print Associated Files<br>\n";
//			print_r($this->associatedFiles);
			
			if($key=='MAXFILESIZE')
			{
				foreach ($this->associatedFiles as $file) 
				{
//					print_r($file);
					$sql = "INSERT INTO ".$tablename." (PhysicalFileNumber,ResourceIDP,FSFileName,FSFileSize,FSFileType) VALUES('".$file['PhysicalFileNumber']."','".$ParentTableID."','".$file['FileName']."','".$file['FileSize']."','".$file['FileType']."')";
//					echo "<br>\n".$sql."<br>\n";
					$database->ExecuteSQL($sql);
				}
			}
	
	//		echo ((new DateTime($keyValues['Start']))->modify("+7 day"))->format("Y-m-d H:i");
	
	//		($keyValues['Start']) = ((new DateTime($keyValues['Start']))->modify("+7 day"))->format("Y-m-d H:i");
	//		($keyValues['End']) = ((new DateTime($keyValues['End']))->modify("+7 day"))->format("Y-m-d H:i");
	//		$keyValues['End']->modify("+7 day");
			return($parentTableID);
		}
	}
	
	public function insertRecord()
	{
		$FieldArray;
		$InsertID=-1;
		$ParentTableID=-1;
		$Table = "";
		foreach($_POST as $key => $value)
		{
	//		echo $key."<br>";
			$parts = explode('_',$key,3);
			if($parts[0]=="InsertRecord")
			{
				if($parts[1]!=$Table)
				{
					if($Table!="")$InsertID=$this->InsertIntoTable($this->database,$Table,$FieldArray,$ParentTableID);
					//echo "Insert ID = ".$InsertID."<br>";
					if($ParentTableID==-1)$ParentTableID=$InsertID;
					$FieldArray=array();
					$Table = $parts[1];
				}
	//			print $value."<br>";
				$FieldArray[$parts[2]] = $value;
			}
		}
//		print_r($FieldArray);
		if($Table!="")$InsertID=$this->InsertIntoTable($this->database,$Table,$FieldArray,$ParentTableID);
		if($ParentTableID==-1)$ParentTableID=$InsertID;
		
		// update submit action
		$actionType = '0';
		switch ($_POST['Action'])
		{
			case 'InsertRecord':
			case 'UpdateRecord':
				$status = '1';
				$actionType = '1';
				break;
				
			case 'ConfirmSubmitResource':
				$actionType = '2';
				$status = '2';
				break;

			default:
				break;
		}
		$date = new DateTime();
		$sql = "INSERT INTO Actions (ResourceID, ActionTypeID, ActionDate, ActionUserID, ActionComment) ";
		$sql .= "VALUES ('".$ParentTableID."',$actionType,'".$date->format('Y-m-d H:i:s')."','".$_POST['UserID']."','".$_POST['ActionComment']."')";
//		echo $sql."<br>";
		$this->database->ExecuteSQL($sql);
		
		// update status
		$sql = "UPDATE ".$_POST['DBTableName']." SET StatusTypeID = '".$status."' WHERE ResourceID = '".$ParentTableID."'";
//		$sql = "INSERT INTO ResourceStatuss (ResourceID, StatusID, Date) ";
//		$sql .= VALUES ('".$ParentTableID."','2','".$date->format('Y-m-d H:i:s')."')";
//		echo $sql."<br>";
		$this->database->ExecuteSQL($sql);
		
	}

	public function updateRecord()
	{
		$this->insertRecord();
		$this->deleteRecord();
		
	}
	
	public function deleteRecord()
	{
		$table = new DBTable($this->database,$_POST['DBTableName']);
		$timeNow = new DateTime("now");
		$sql = "UPDATE ".$_POST['DBTableName']." SET DeletedWhen = '".$timeNow->format("Y-m-d H:i")."', DeletedBy = '".$this->userID."' ";
		$sql .= " WHERE ".$table->getPrimaryKey()."=".$this->recordID;
//		echo $sql;
		$this->database->ExecuteSQL($sql);
	}
	

	
	// Edit/Update/Delete Record to do
	
	
	// SubmitSelect
	// SelectTable has OriginalTableName OriginalID 
	// eg MusicEvents has MusicEventID and EventID
	
public function submitSelect($tableName,$sourceTableName)
	{
		// first delete previous settings
		
//		echo "Source = ".$sourceTableName."  table = ".$tableName."<br\n";
		
		$sql = "TRUNCATE TABLE ".$tableName;
		$this->database->ExecuteSQL($sql);
		
		// get new values
		$selectedSourceIDs = array();
					
		foreach($_POST as $key => $value)
		{
//			echo $key."<br>";
			$parts = explode('_',$key,3);
//			print_r ($parts)."<br>";
			if(($parts[0]=="SubmitSelect")&&($parts[1]==$tableName))
			{
			array_push($selectedSourceIDs,$parts[2]);			
			}
		}
		
//		print_r($selectedSourceIDs);
		foreach($selectedSourceIDs as $SourceID)
		{
			$sql = "INSERT INTO ".$tableName." (".substr($sourceTableName,0,-1)."ID) VALUES (".$SourceID.")";
//			echo $sql."<br>\n";
			$this->database->ExecuteSQL($sql);
		}
		
	}
		
}